package com.mingmen.canting.caigourenyuan;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.canting.R;

import com.mingmen.canting.adapter.CaiGouZhongAdapter;

import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;

import com.mingmen.canting.fragment.BaseFragment;

import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.CaiGouRightModel;

import com.mingmen.canting.model.ImageModel;
import com.mingmen.canting.util.DividerItemDecoration;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.SharePreferenceUtil;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class CaigouZhongRightFragment extends BaseFragment implements CaiGouZhongAdapter.OnitemClick {
    private SwipeRecyclerView mRecyclerView;
    private String mTitle;

    @Override
    public void onItemClick(View view, int position, List<CaiGouRightModel.DetailsBean> dataBeanList, String supplierName) {
        Intent intent;
        switch (view.getId()) {
            case R.id.btn_detail:
                intent = new Intent(getActivity(), ShopDetailActivity.class);
                intent.putExtra("supplierId", dataBeanList.get(position).getBillId());
                intent.putExtra("billId", dataBeanList.get(position).getApplyId());
                intent.putExtra("partCancelFlag", partCancelFlag);
                intent.putExtra("partArriveFlag", partArriveFlag);
                intent.putExtra("partRefuseFlag", partRefuseFlag);
                intent.putExtra("shipping", dataBeanList.get(position).getShipping());
                intent.putExtra("supplierName", supplierName);

                startActivity(intent);
                break;
            case R.id.btn_save:
//                    Toast.makeText(getActivity(), dataBeanList.get(position).getBillId() + "保存订单", Toast.LENGTH_SHORT).show();
                saveBileImage(token, dataBeanList.get(position).getBillId());


                break;
            case R.id.btn_submit:
                Log.d("getSupplierName", supplierName);

                if (supplierName.equals("线下自采")) {
                    intent = new Intent(getActivity(), QueRenShouZiCaiActivity.class);
                    intent.putExtra("supplierId", dataBeanList.get(position).getSupplierId());
                    intent.putExtra("billId", dataBeanList.get(position).getBillId());
                    intent.putExtra("supplierName", dataBeanList.get(position).getSupplierName());
                    intent.putExtra("partCancelFlag", partCancelFlag);
                    intent.putExtra("partArriveFlag", partArriveFlag);
                    intent.putExtra("partRefuseFlag", partRefuseFlag);
                    startActivity(intent);
                } else {
                    intent = new Intent(getActivity(), QueRenShouActivity.class);
                    intent.putExtra("supplierId", dataBeanList.get(position).getSupplierId());
                    intent.putExtra("billId", dataBeanList.get(position).getBillId());
                    intent.putExtra("supplierName", dataBeanList.get(position).getSupplierName());
                    intent.putExtra("partCancelFlag", partCancelFlag);
                    intent.putExtra("partArriveFlag", partArriveFlag);
                    intent.putExtra("partRefuseFlag", partRefuseFlag);
                    startActivity(intent);
                }
        }
    }

    private class NetWorkChangeReceiver extends BroadcastReceiver implements CaiGouZhongAdapter.OnitemClick {
        @Override
        public void onReceive(Context context, Intent intent) {
            //系统服务类
            String pos = intent.getStringExtra("pos");
            Log.d("pospospos", pos);
            String strData = intent.getStringExtra("strData");
            Log.d("CaiGouzhongStrData", strData);
            if (dataBeanList.size() > 0) {
                dataBeanList.clear();
            }
            CaiGouRightModel caiGouRightModel = GsonUtil.GsonToBean(strData, CaiGouRightModel.class);
//            dataBeanList.addAll(caiGouRightModel.getDetails());
            dataBeanList = caiGouRightModel.getDetails();
            partCancelFlag = caiGouRightModel.getPartCancelFlag();
            partArriveFlag = caiGouRightModel.getPartArriveFlag();
            partRefuseFlag = caiGouRightModel.getPartRefuseFlag();
            caiGouRuKuAdapter = new CaiGouZhongAdapter(getActivity(), strData);
            mRecyclerView.setAdapter(caiGouRuKuAdapter);
            caiGouRuKuAdapter.setOnitemClickLintener(this);
//            caiGouRuKuAdapter.setDataList(dataBeanList);
        }

        @Override
        public void onItemClick(View view, int position, List<CaiGouRightModel.DetailsBean> dataBeanList, String supplierName) {
            Intent intent;

            switch (view.getId()) {
                case R.id.btn_detail:

                    intent = new Intent(getActivity(), ShopDetailActivity.class);
                    intent.putExtra("supplierId", dataBeanList.get(position).getBillId());
                    intent.putExtra("billId", dataBeanList.get(position).getApplyId());
                    intent.putExtra("partCancelFlag", partCancelFlag);
                    intent.putExtra("partArriveFlag", partArriveFlag);
                    intent.putExtra("partRefuseFlag", partRefuseFlag);
                    intent.putExtra("supplierName", supplierName);
                    intent.putExtra("shipping", dataBeanList.get(position).getShipping());
                    startActivity(intent);
                    break;
                case R.id.btn_save:
//                    Toast.makeText(getActivity(), dataBeanList.get(position).getBillId() + "保存订单", Toast.LENGTH_SHORT).show();
                    saveBileImage(token, dataBeanList.get(position).getBillId());
                    break;
                case R.id.btn_submit:
                    Log.d("getSupplierName", supplierName);

                    if (supplierName.equals("线下自采")) {
                        intent = new Intent(getActivity(), QueRenShouZiCaiActivity.class);
                        intent.putExtra("supplierId", dataBeanList.get(position).getSupplierId());
                        intent.putExtra("billId", dataBeanList.get(position).getBillId());
                        intent.putExtra("supplierName", dataBeanList.get(position).getSupplierName());
                        intent.putExtra("partCancelFlag", partCancelFlag);
                        intent.putExtra("partArriveFlag", partArriveFlag);
                        intent.putExtra("partRefuseFlag", partRefuseFlag);
                        startActivity(intent);
                    } else {
                        intent = new Intent(getActivity(), QueRenShouActivity.class);
                        intent.putExtra("supplierId", dataBeanList.get(position).getSupplierId());
                        intent.putExtra("billId", dataBeanList.get(position).getBillId());
                        intent.putExtra("supplierName", dataBeanList.get(position).getSupplierName());
                        intent.putExtra("partCancelFlag", partCancelFlag);
                        intent.putExtra("partArriveFlag", partArriveFlag);
                        intent.putExtra("partRefuseFlag", partRefuseFlag);
                        startActivity(intent);
                    }


                    break;
            }
        }
    }

    private IntentFilter intentFilter;
    private NetWorkChangeReceiver netWorkChangeReceiver;

    public static CaigouZhongRightFragment getInstance(String title) {
        CaigouZhongRightFragment sf = new CaigouZhongRightFragment();
        sf.mTitle = title;
        return sf;
    }

    public void saveBileImage(String token, String billId) {
        HttpResponse.restOrderImage(token, billId, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(getActivity(), "当前无数据", Toast.LENGTH_SHORT).show();
                }


                Log.d("saveBileImage", s);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ImageModel imageModel = new ImageModel();
                        imageModel = GsonUtil.GsonToBean(s, ImageModel.class);
                        Bitmap bp = returnBitMap(imageModel.getData().getData());
                        saveImageToPhotos(mContext, bp);


                    }
                }).start();

//                MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, "title", "description");
            }
        });
    }


    private void init() {

        intentFilter = new IntentFilter();
        intentFilter.addAction("canting.chushizhang.ChushiZhangRightFragment");
        netWorkChangeReceiver = new NetWorkChangeReceiver();
        //注册广播
        getActivity().registerReceiver(netWorkChangeReceiver, intentFilter);
    }

    CaiGouZhongAdapter caiGouRuKuAdapter;

    String right;

    List<CaiGouRightModel.DetailsBean> dataBeanList = new ArrayList<>();
    String partCancelFlag;
    String partArriveFlag;
    String partRefuseFlag;
    String token;

    @Override
    public View initView() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_caigoudan_right, null);
        TextView card_title_tv = (TextView) view.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);
        mRecyclerView = view.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        //        mRecyclerView.addItemDecoration(new DefaultItemDecoration(ContextCompat.getColor(getActivity(), R.color.divider_color)));
        DividerItemDecoration itemDecorationHeader = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST);
        itemDecorationHeader.setDividerDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.divider_main_bg_height_1));
        mRecyclerView.addItemDecoration(itemDecorationHeader);
        right = getArguments().getString("right");
        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        Log.d("RIGHTRIGHT", right);
        if (right.length() > 10) {
            CaiGouRightModel caiGouRightModel = GsonUtil.GsonToBean(right, CaiGouRightModel.class);
            partCancelFlag = caiGouRightModel.getPartCancelFlag();
            partArriveFlag = caiGouRightModel.getPartArriveFlag();
            partRefuseFlag = caiGouRightModel.getPartRefuseFlag();
            SharePreferenceUtil.put(getActivity(), "partCancelFlag", partCancelFlag);
            SharePreferenceUtil.put(getActivity(), "partArriveFlag", partArriveFlag);
            SharePreferenceUtil.put(getActivity(), "partRefuseFlag", partRefuseFlag);

            Log.d("partCancelFlag", partCancelFlag);
            dataBeanList.addAll(caiGouRightModel.getDetails());
            caiGouRuKuAdapter = new CaiGouZhongAdapter(getActivity(), right);
            mRecyclerView.setAdapter(caiGouRuKuAdapter);
            caiGouRuKuAdapter.setOnitemClickLintener(this);
//            caiGouRuKuAdapter.setDataList(dataBeanList);
        }

        init();

        return view;
    }

    @Override
    public void initData() {

    }


    /**
     * 保存图片到本地相册
     */
    private void saveImageToPhotos(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
//            mHandler.obtainMessage(SAVE_FAILURE).sendToTarget();
            return;
        }
        // 最后通知图库更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);


    }


    /**
     * 将URL转化成bitmap形式
     *
     * @param url
     * @return bitmap type
     */
    public final static Bitmap returnBitMap(String url) {
        URL myFileUrl;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
            HttpURLConnection conn;
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }


}
